<?php

class Memo extends Controller {
  
  function Memo() {
    parent::Controller();
    $this->load->model('Memo_model', 'p');
  }
  
  function index($cari=false) {
     
    if (!$this->session->userdata('username')) {
      $data['isLogin'] = FALSE;
      redirect("/login", "location");
    } else {
      $data['isLogin'] = TRUE;
      $data['username'] = $this->session->userdata('username');
      $data['role'] = $this->session->userdata('role');
      $data['kd_unit'] = $this->session->userdata('kode_unit');    
    }
    
    $carin = $this->input->post('cari');            
    $tgl_awal =  $this->input->post('sdate')?DMY2YMD(str_replace("/", TGL_SEPARATOR,  $this->input->post('sdate')), TGL_SEPARATOR):"";
    $tgl_akhir = $this->input->post('edate')?DMY2YMD(str_replace("/", TGL_SEPARATOR,  $this->input->post('edate')), TGL_SEPARATOR):""    ;
    
    $this->load->model('Datum_model', 'd');
    $namauser = $this->session->userdata('username');  
    
      $list_arsip = $this->p->list_isi();   
      $wcari = "(perihal LIKE '%$carin%' OR tanggal LIKE '%$carin%') AND (tanggal between '$tgl_awal' AND '$tgl_akhir')";  
    
    $tgl = array(
        'tgl_awal' =>  $this->input->post('sdate'),
        'tgl_akhir' => $this->input->post('edate')
    );               
    $this->session->set_userdata($tgl);
    if($cari==true) {
      $data['link_excel'] = base_url().'memo/export_ToExcel/'.$tgl_awal.'/'.$tgl_akhir.'/'.$carin; 
      if($carin =="") {
    $wcari = "tanggal between '$tgl_awal' AND '$tgl_akhir'"; 
    $list_isi = $this->p->list_isi($wcari); 
      }
      else{  
    $wcari = "(perihal LIKE '%$carin%' OR tanggal LIKE '%$carin%')";
    $list_isi = $this->p->list_isi($wcari);
      } 
    } else {
      $data['link_excel'] = base_url().'memo/export_ToExcel/'; 
      $list_isi = $list_arsip;            
    }
    
    $tabel_header = $this->p->list_header();
    $nama_variabel = 'data';
    $isi = 'var '.$nama_variabel.'='.$list_isi;
    
    $data['additional_js'] = '
        <script type="text/javascript">
        function deleteRow(id) {
            var txt = \'Anda yakin mau menghapus data memo ini?<input type="hidden" id="row-id" name="row-id" value="\'+ id +\'" />\';
                url = "'.base_url().'memo/hapus/"+id;
             $.ajax({
               type: "POST",
               url: "'.base_url().'memo/bisa_dihapus/"+id,
               success: function(msg) {
                 if (msg==\'bisa\') {
                    $.prompt(txt,{
                        buttons:{Hapus:true, Batal:false},
                        callback: function(v){
                            if(v) {
                                $("tr#row-"+id).fadeOut("slow", function() {
                                    $("tr#row-"+id).remove();
                                });
                                top.location.href=url;
                            }
                        }
                    });
                 } else {
                    $.prompt(\'Maaf, data memo tidak dapat dihapus dikarenakan terkait dengan data lain.\');
                 }
               }
            });
        }
        </script>
        <script type="text/javascript">
            '.$isi.'

            // This file demonstrates the different options of the pagination plugin
            // It also demonstrates how to use a JavaScript data structure to
            // generate the paginated content and how to display more than one
            // item per page with items_per_page.

            /**
             * Callback function that displays the content.
             *
             * Gets called every time the user clicks on a pagination link.
             *
             * @param {int}page_index New Page index
             * @param {jQuery} jq the container with the pagination links as a jQuery object
             */
            function pageselectCallback(page_index, jq){
                // Get number of elements per pagionation page from form
                var items_per_page = '.ROW_PER_PAGE.';
                var max_elem = Math.min((page_index+1) * items_per_page, '.$nama_variabel.'.length);
                var newcontent = \''.$tabel_header.'\';

                // Iterate through a selection of the content and build an HTML string
                for(var i=page_index*items_per_page;i<max_elem;i++)
                {
                    newcontent += '.$nama_variabel.'[i];
                }

                newcontent += \'</tbody></table>\';

                // Replace old content with new content
                $("#isi_tabel").html(newcontent);

                //$("#scrollable").tablesorter({sortList: [[1,0]], headers: { 0:{sorter: false}, 2:{sorter: false}, 8:{sorter: false}, 11:{sorter: false} }, widthFixed: true, widgets: [\'zebra\']});

                // Prevent click eventpropagation
                return false;
            }

            // When document has loaded, initialize pagination and form
            $(document).ready(function(){
                $("#paginasi").pagination('.$nama_variabel.'.length, {
                    items_per_page:'.ROW_PER_PAGE.',
                    num_edge_entries: '.NUM_EDGE_ENTRIES.',
                    next_text: \''.TEKS_NEXT.'\',
                    prev_text: \''.TEKS_PREV.'\',
                    next_show_always: '.ALWAYS_SHOW_NEXT.',
                    prev_show_always: '.ALWAYS_SHOW_PREV.',
                    callback:pageselectCallback
                });
            
            });

        </script>
        ';
    #$cari = Datum_model::form_cari(base_url().'index.php/memo/index/true');
    $data['judul'] = 'Memo';
    $data['tampilkan_menu'] = true;
    $data['teks_link_tambah'] = 'Memo Baru';
    $data['link_tambah'] = base_url().'memo/form_isian/';
      
   
    #$data['filter'] = $cari;//'Filter: '.combo_kategori_memo('kategori', '').' ';
    
    $this->load->view('view_main',$data);
  }
  
  function _setRules($is_baru=true) {
    return '
                    //set the rules for the field names
                    rules: {
                        tanggal: { required: true },
                        pengirim: { required: true },
                        tujuan: { required: true},
                        perihal: { required: true },
                        isi: { required: true }
                    },
                    //set messages to appear inline
                    messages: {
                        tanggal: "Tanggal memo wajib diisi",
                        pengirim: "Pengirim wajib diisi",
                        tujuan: "Tujuan wajib diisi",            
                        perihal: "Perihal wajib diisi",
                        isi: "Isi memo wajib diisi"
                    }
        ';
  }
  
  function _setJsForm($additional_string,$is_baru=true) {
    $ret = '
        <script type="text/javascript">
            $(function() {
                $("#div_viewer").hide();
                $("#tanggal").focus();
                $(\'.date-pick\').datePicker({startDate:\'01/01/2008\'});
                $("#btn_kembali").click( function() {
                    window.location = \''.base_url().'memo\';
                });
                // validate contact form on keyup and submit
                $("form").validate({
                    '.$this->_setRules($is_baru).'
                });
                $("#kode_viewer").change(function(){
                    var kode = $("#kode_viewer").val();
                    if (kode == 1) {
                        $("#div_viewer").show("slow");
                    } 
                });
                
                $("#tujuan").autocomplete("'.base_url().'autocomplit/namauser", {
                    mustMatch: true,
                    selectFirst: false
                    
                    });
                    

            });
        </script>
        ';
    return $ret;
  }
  
  function _setCSS() {
    return '
            <style type="text/css">
            a.dp-choose-date {
                float: left;
                width: 16px;
                height: 16px;
                padding: 0;
                margin: 5px 3px 0;
                display: block;
                text-indent: -2000px;
                overflow: hidden;
                background: url('.base_url().'templates/images/cal.gif) no-repeat;
            }
            a.dp-choose-date.dp-disabled {
                background-position: 0 -20px;
                cursor: default;
            }
            /* makes the input field shorter once the date picker code
             * has run (to allow space for the calendar icon
             */
            input.dp-applied {
                width: 140px;
                float: left;
            }
            </style>
        ';
  }
  
  function form_isian() {
    if (!$this->session->userdata('username')) {
      $data['isLogin'] = FALSE;
      redirect("/login", "location");
    } else {
      $data['isLogin'] = TRUE;
      $data['username'] = $this->session->userdata('username');
      $data['role'] = $this->session->userdata('role');
    }
    error_reporting(E_ALL); 
    ini_set("display_errors", 1);
    $form_action = base_url().'index_arsip.php/memo/simpan';
    $form_id = 'form_memo';
    
    $data['additional_js'] = $this->_setJsForm("");
    $data['additional_css'] = $this->_setCSS();
    
    $data['judul'] = 'Memo Baru ';
    
    $data['list_data'] = $this->p->entry_form($form_id,$form_action);
    $this->load->view('view_farsip', $data);
  }
  
  function simpan($is_update=FALSE, $id='') {
    if (!$this->session->userdata('username')) {
      $data['isLogin'] = FALSE;
      redirect("/login", "location");
    }
    #$arr['kode_unit'] = $this->session->userdata('kode_unit');
    $arr['tanggal'] = $this->input->post('tanggal')?DMY2YMD(str_replace("/", TGL_SEPARATOR, $this->input->post('tanggal')), TGL_SEPARATOR):date('Y-m-d');
    $arr['pengirim'] = $this->input->post('pengirim')?$this->input->post('pengirim'):"";
    $arr['tujuan'] = $this->input->post('tujuan')?$this->input->post('tujuan'):"";
    $arr['perihal'] = $this->input->post('perihal')?$this->input->post('perihal'):"";
    $arr['isi'] = $this->input->post('isi')?$this->input->post('isi'):"";
    
    if ($is_update) {
      //
    }
    
    
    if ($is_update) {
      $arr['user_update'] = $this->session->userdata('username');
      $arr['tgl_update'] = date('Y-m-d H:i:s');
      $this->p->simpan($arr, $is_update, $id);
    } else {
      $arr['user_input'] = $this->session->userdata('username'); 
      $this->p->simpan($arr);
      $id = $this->db->insert_id();
      if ($this->db->affected_rows() >0 ) {
    //$this->p->kirim_email($arr['tujuan'], $arr['perihal'], $arr['isi'], $id);
      }
    }
    
    redirect('memo', 'refresh');
  }
  
  function form_edit($id,$preview=false) {
    if (!$this->session->userdata('username')) {
      $data['isLogin'] = FALSE;
      redirect("/login", "location");
    } else {
      $data['isLogin'] = TRUE;
      $data['username'] = $this->session->userdata('username');
      $data['role'] = $this->session->userdata('role');
    }
    
    $data['additional_js'] = $this->_setJsForm("",false);
    $data['additional_css'] = $this->_setCSS();
    
    $this->db->where(array('id' => $id));
    $q = $this->db->get('memo');
    if ($q->num_rows() > 0) {
      $row = $q->row();
      $arr['tanggal']     = YMD2DMY(trimTime($row->tanggal), TGL_SEPARATOR);
      $arr['pengirim']    = $row->pengirim;
      $arr['tujuan']      = $row->tujuan;
      $arr['perihal']     = $row->perihal;
      $arr['isi']         = $row->isi;
      
      $arr['created_by']  = sprintf('%s pada %s', $row->user_input, YMD2Indo(trimTime($row->tgl_input), TGL_SEPARATOR));
      if ($row->user_update!='') {
    $arr['last_update']        = sprintf('%s pada %s', $row->user_update, YMD2Indo(trimTime($row->tgl_update), TGL_SEPARATOR));
      }
      $arr['email_sent'] = $row->email_sent;
      
      $form_action = base_url().'index_arsip.php/memo/simpan/true/'.$id;
      $form_id = 'form_memo';
      
      if($preview==false)
    $data['judul'] = 'Ubah Memo';
      else $data['judul'] = $row->perihal;
      $data['list_data'] = $this->p->entry_form($form_id,$form_action,$arr,$preview);
      $this->load->view('view_farsip', $data);
    } else {
      redirect('memo', 'refresh');
    }
  }
  
  
  function hapus($id) {
    $this->db->where('id', $id);
    $this->db->delete('memo');
    if ($this->db->affected_rows()>0) {
      //
    }
    redirect('memo', 'refresh');
  }
  
  
  function bisa_dihapus($id) {
    echo 'bisa';
  }
  
  function unduh_memo($id) {
    /*  if (!$this->session->userdata('username')) {
            $data['isLogin'] = FALSE;
            redirect("/login", "location");
        } else {
            $data['isLogin'] = TRUE;
            $data['username'] = $this->session->userdata('username');
            $data['role'] = $this->session->userdata('role');
        }
    */
    $this->db->where("idpta_memo = $id" );      
    $q = $this->db->get('memo');
    
    $this->load->model('Datum_model'); 
    foreach($q->result() as $row) {   
      $namafile = Datum_model::getData('namafile', 'files', array('idpta_files' => $row->pta_id_files));      
      $no = $row->pta_id_files;
      $Count = $row->hits;
      $FileURL = base_url().substr(BASE_UPLOAD_memo,2).$no.$namafile;
      
      header('Location: '.$FileURL);
      
      $arr = Array('hits' => $Count+1);
      $this->db->where('idpta_memo', $id);
      $this->db->update('memo', $arr);
    }
    
    /* $this->load->model('Datum_model', 'd');
        $id_file = $this->d->getData('pta_id_files', 'memo', array('idpta_memo'=>$id));
        $namafile = $this->d->getData('namafile', 'files', array('idpta_files'=>$id_file));
        
        $data['judul'] = $this->d->getData('judul', 'memo', array('idpta_memo'=>$id));
        $data['isi'] = '<center><p><img src="'.base_url().'uploads/memo/'.$id_file.$namafile.'" /><p></center>';
        $data['link_kembali'] = 'javascript:window.close();';
        $this->load->view('view_blank', $data);
       redirect("../uploads/".$namafile, "location");     */
  }
  function export_ToExcel($tgl_awal="",$tgl_akhir="",$carin="") {
    // load the library
    $this->load->library('excel');
    
    // access the class by using the worksheet variable
    $sheet = $this->excel->workbook;
    $sheet->setActiveSheetIndex(0);
    $sheet->getActiveSheet()->getDefaultStyle()->getFont()->setName('Calibri');
    $sheet->getActiveSheet()->getDefaultStyle()->getFont()->setSize(9);
    $sheet->getActiveSheet()->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
    $sheet->getActiveSheet()->getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
    
    $styleArray = array(
        'font' => array(
            'bold' => true,
            'size'=>12,
        ),
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        ),
        'borders' => array(
            'top' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'bottom' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'left' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'right' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
        ),
    );
    //No    Tanggal    Pengirim    Tujuan    Perihal    Email Sent
    $sheet->getActiveSheet()->getStyle('B3')->applyFromArray($styleArray);
    $sheet->getActiveSheet()->getStyle('C3')->applyFromArray($styleArray);
    $sheet->getActiveSheet()->getStyle('D3')->applyFromArray($styleArray);
    $sheet->getActiveSheet()->getStyle('E3')->applyFromArray($styleArray);
    $sheet->getActiveSheet()->getStyle('F3')->applyFromArray($styleArray);
    //Header Table
    $sheet->getActiveSheet()->setCellValue('B3', 'NO');
    $sheet->getActiveSheet()->setCellValue('C3', 'TANGGAL');
    $sheet->getActiveSheet()->setCellValue('D3', 'PENGIRIM');
    $sheet->getActiveSheet()->setCellValue('E3', 'TUJUAN');
    $sheet->getActiveSheet()->setCellValue('F3', 'PERIHAL');
    
    $styleArray2 = array(
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
            'vertical' => PHPExcel_Style_Alignment::VERTICAL_TOP,
        ),
        'borders' => array(
            'top' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'bottom' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'left' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'right' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
        ),
        
    );
    
    $styleArray3 = array(
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
            'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
        ),
        'borders' => array(
            'top' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'bottom' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'left' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
            'right' => array(
                'style' => PHPExcel_Style_Border::BORDER_THIN,
            ),
        ),
        
    );
    //Data
    
    // echo $tgl_awal;
    // echo $tgl_akhir;
    // echo $carin;
    if($tgl_awal!="" && $tgl_akhir!="" || $carin!="") {
      $wcari = "(tanggal between '$tgl_awal' AND '$tgl_akhir')";  
      $this->db->where($wcari);
    }
    
    $this->db->order_by('tanggal desc');
    $this->db->where('email_sent = 0');
    $q = $this->db->get('memo');//echo     $this->db->last_query();
    $order   = array("\r\n", "\n", "\r", "'");
    $replace = ' ';
    $i = 1;
    $baris = 4;
    foreach($q->result() as $row) {
      $sheet->getActiveSheet()->getStyle('B'.$baris.':G'.$baris)->getAlignment()->setWrapText(true);
      $sheet->getActiveSheet()->setCellValue('B'.$baris, $i);
      $sheet->getActiveSheet()->getStyle('B'.$baris)->applyFromArray($styleArray3);//style
      
      $sheet->getActiveSheet()->getStyle('C'.$baris)->applyFromArray($styleArray2);//style
      $sheet->getActiveSheet()->getColumnDimension('C')->setWidth(64);//style
      $sheet->getActiveSheet()->setCellValue('C'.$baris, YMD2Indo(trimTime($row->tanggal), TGL_SEPARATOR ));
      
      $sheet->getActiveSheet()->getStyle('D'.$baris)->applyFromArray($styleArray2);//style
      $sheet->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);//style
      $sheet->getActiveSheet()->setCellValue('D'.$baris,$row->pengirim);
      
      $sheet->getActiveSheet()->getStyle('E'.$baris)->applyFromArray($styleArray2);
      $sheet->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);//style
      $sheet->getActiveSheet()->setCellValue('E'.$baris, $row->tujuan);
      
      $sheet->getActiveSheet()->getStyle('F'.$baris)->applyFromArray($styleArray2);
      $sheet->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);//style
      $sheet->getActiveSheet()->setCellValue('F'.$baris,str_replace($order, $replace, $row->perihal));
      
      $baris++;
      $i++;
    }
    
    // Hide GridLine
    $sheet->getActiveSheet()->setShowGridlines(FALSE);
    $sheet->getActiveSheet()->setTitle('Report Memo');
    // output the workbook
    $this->excel->send_to_browser('memo_'.date('dmY').'.xls','Excel5'); // second parameter sets file format 
  }
  
}

/* End of file memo.php */
/* Location: ./system/application/arsip/controllers/memo.php */